package com.git.hui.yinshua.biz.goods.dao.repository;

import com.git.hui.yinshua.api.model.constants.GlobalConstants;
import com.git.hui.yinshua.biz.goods.dao.domain.GoodsDetailEntity;
import com.git.hui.yinshua.biz.goods.dao.domain.GoodsEntity;
import com.git.hui.yinshua.biz.goods.dao.domain.GoodsSpecEntity;
import com.git.hui.yinshua.biz.goods.dao.mapper.GoodsMapper;
import com.git.hui.yinshua.biz.rest.models.goods.req.GoodsQueryReq;
import com.git.hui.yinshua.biz.rest.models.goods.req.OperateGoodsReq;
import com.git.hui.yinshua.biz.rest.models.goods.rsp.GoodsDetailDto;
import com.git.hui.yinshua.biz.rest.models.goods.rsp.GoodsSpecDto;
import com.git.hui.yinshua.biz.util.PriceUtil;
import com.google.common.base.Joiner;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 商品操作
 *
 * @author YiHui
 * @date 2024/6/13
 */
@Repository
public class GoodsRepository {
    @Autowired
    private GoodsMapper goodsMapper;

    /**
     * 保存商品
     *
     * @param req
     * @return
     */
    public GoodsEntity addGoods(OperateGoodsReq req) {
        GoodsEntity entity = new GoodsEntity();
        entity.setGoodsName(req.getName());
        entity.setCategoryId(req.getCid());
        entity.setIntro(req.getIntro() == null ? "" : req.getIntro());
        entity.setThumb(CollectionUtils.isEmpty(req.getThumb()) ? "" : Joiner.on(",").join(req.getThumb()));
        entity.setPrice(PriceUtil.toCentPrice(req.getPrice()));
        entity.setDiscountPrice(StringUtils.isBlank(req.getDiscountPrice()) ? entity.getPrice() : PriceUtil.toCentPrice(req.getDiscountPrice()));

        entity.setMinCnt(req.getMinCnt() == null || req.getMinCnt() <= 0 ? 1 : req.getMinCnt());
        entity.setSalesCnt(0);
        entity.setStock(req.getStock() == null ? GlobalConstants.GoodsApi.NO_LIMIT_STOCK : req.getStock());
        entity.setRecommend(req.getRecommend() == null ? 0 : (req.getRecommend() == 1 ? GlobalConstants.GoodsApi.GOODS_RECOMMEND_STATE : GlobalConstants.GoodsApi.GOODS_UNRECOMMEND_STATE));
        entity.setState(req.getState() == null ? GlobalConstants.GoodsApi.GOODS_OFFLINE_STATE : (req.getState() == 1 ? GlobalConstants.GoodsApi.GOODS_ONLINE_STATE : GlobalConstants.GoodsApi.GOODS_OFFLINE_STATE));
        entity.setPublishAt(null);
        if (Objects.equals(entity.getState(), GlobalConstants.GoodsApi.GOODS_ONLINE_STATE)) {
            entity.setPublishAt(System.currentTimeMillis());
        }
        // 拼团配置
        entity.setPtEnable(BooleanUtils.isTrue(req.getPtEnable()) ? GlobalConstants.GoodsApi.PT_ENABLE : GlobalConstants.GoodsApi.PT_DISABLE);
        entity.setPtNum(req.getPtNum());
        entity.setPtTimePeriod(req.getPtTimePeriod());
        goodsMapper.saveGoods(entity);
        return entity;
    }

    public boolean addGoodsSpecs(GoodsEntity goods, List<GoodsSpecDto> specList) {
        if (CollectionUtils.isEmpty(specList)) {
            return true;
        }

        List<GoodsSpecEntity> list = new ArrayList<>();
        specList.forEach(spec -> {
            String specValue = spec.getSpec();
            if (specValue == null) {
                return;
            }
            GoodsSpecEntity entity = new GoodsSpecEntity();
            entity.setGoodsSpecs(specValue);
            entity.setGoodsId(goods.getId());
            entity.setGoodsStock(spec.getStock() == null ? -1 : spec.getStock());
            entity.setGoodsPrice(StringUtils.isBlank(spec.getPrice()) ? goods.getPrice() : PriceUtil.toCentPrice(spec.getPrice()));
            entity.setDiscountPrice(StringUtils.isBlank(spec.getDiscountPrice()) ? goods.getDiscountPrice() : PriceUtil.toCentPrice(spec.getDiscountPrice()));
            entity.setSalesCnt(0);
            entity.setMinCnt(spec.getMinCnt() == null ? goods.getMinCnt() : spec.getMinCnt());
            entity.setPtEnable(goods.getPtEnable());
            entity.setPtNum(spec.getPtNum());
            entity.setPtTimePeriod(spec.getPtTimePeriod());
            list.add(entity);
        });
        if (list.isEmpty()) {
            return true;
        }
        goodsMapper.saveSpecs(list);
        return true;
    }

    public boolean addDetails(GoodsEntity goods, List<GoodsDetailDto> detailList) {
        if (CollectionUtils.isEmpty(detailList)) {
            return true;
        }

        List<GoodsDetailEntity> list = new ArrayList<>();
        detailList.forEach(detail -> {
            GoodsDetailEntity entity = new GoodsDetailEntity();
            entity.setGoodsId(goods.getId());
            entity.setTitle(detail.getTitle() == null ? "" : detail.getTitle());
            entity.setIntro(detail.getIntro() == null ? "" : detail.getIntro());
            entity.setImgs(CollectionUtils.isEmpty(detail.getImgs()) ? "" : Joiner.on(",").join(detail.getImgs()));
            entity.setSort(detail.getSort() == null ? 0 : detail.getSort());
            list.add(entity);
        });
        if (list.isEmpty()) {
            return true;
        }
        goodsMapper.saveDetails(list);
        return true;
    }


    public boolean updateGoods(OperateGoodsReq req) {
        GoodsEntity entity = new GoodsEntity();
        entity.setId(req.getGoodsId());
        entity.setGoodsName(req.getName());
        entity.setCategoryId(req.getCid());
        entity.setIntro(req.getIntro());
        entity.setThumb(CollectionUtils.isEmpty(req.getThumb()) ? null : Joiner.on(",").join(req.getThumb()));
        entity.setPrice(PriceUtil.toCentPrice(req.getPrice()));
        entity.setDiscountPrice(StringUtils.isBlank(req.getDiscountPrice()) ? entity.getPrice() : PriceUtil.toCentPrice(req.getDiscountPrice()));
        entity.setMinCnt(req.getMinCnt());
        entity.setState(req.getState());
        entity.setRecommend(req.getRecommend());
        if (req.getState() != null && Objects.equals(req.getState(), goodsMapper.queryGoodsState(req.getGoodsId()))) {
            entity.setPublishAt(System.currentTimeMillis());
        }

        entity.setStock(req.getStock());
        if (req.getPtEnable() != null) {
            entity.setPtEnable(req.getPtEnable() ? GlobalConstants.GoodsApi.PT_ENABLE : GlobalConstants.GoodsApi.PT_DISABLE);
            entity.setPtNum(req.getPtNum());
            entity.setPtTimePeriod(req.getPtTimePeriod());
        }
        return goodsMapper.updateGoods(entity) > 0;
    }

    public boolean updateOnlineState(Integer goodsId, boolean online) {
        GoodsEntity entity = new GoodsEntity();
        entity.setId(goodsId);
        entity.setState(online ? GlobalConstants.GoodsApi.GOODS_ONLINE_STATE : GlobalConstants.GoodsApi.GOODS_OFFLINE_STATE);
        entity.setPublishAt(System.currentTimeMillis());
        return goodsMapper.updateGoods(entity) > 0;
    }

    public boolean updateRecommend(Integer goodId, boolean recommend) {
        GoodsEntity entity = new GoodsEntity();
        entity.setId(goodId);
        entity.setRecommend(recommend ? GlobalConstants.GoodsApi.GOODS_RECOMMEND_STATE : GlobalConstants.GoodsApi.GOODS_UNRECOMMEND_STATE);
        return goodsMapper.updateGoods(entity) > 0;
    }

    /**
     * 更新商品销量
     *
     * @param goodsId      商品id
     * @param incrSalesCnt 增加的销量数
     * @return
     */
    public boolean updateSalesCnt(Integer goodsId, Integer incrSalesCnt) {
        GoodsEntity entity = new GoodsEntity();
        entity.setId(goodsId);
        entity.setSalesCnt(incrSalesCnt);
        return goodsMapper.updateGoods(entity) > 0;
    }

    public boolean updateSpecs(Integer goodsId, List<GoodsSpecDto> specs) {
        if (CollectionUtils.isEmpty(specs)) {
            return true;
        }
        List<GoodsSpecEntity> list = new ArrayList<>();
        specs.forEach(spec -> {
            GoodsSpecEntity entity = new GoodsSpecEntity();
            entity.setId(spec.getSpecId());
            entity.setGoodsId(goodsId);
            entity.setGoodsStock(spec.getStock());
            entity.setGoodsSpecs(spec.getSpec());
            entity.setGoodsPrice(StringUtils.isBlank(spec.getPrice()) ? null : PriceUtil.toCentPrice(spec.getPrice()));
            entity.setDiscountPrice(StringUtils.isBlank(spec.getDiscountPrice()) ? null : PriceUtil.toCentPrice(spec.getDiscountPrice()));
            entity.setMinCnt(spec.getMinCnt());
            if (Objects.equals(spec.getSpec(), "") || "[]".equals(spec.getSpec())) {
                // 没有属性时，移除这一项
                entity.setDeleted(1);
            }
            if (spec.getPtEnable() != null) {
                entity.setPtEnable(spec.getPtEnable() ? GlobalConstants.GoodsApi.PT_ENABLE : GlobalConstants.GoodsApi.PT_DISABLE);
                entity.setPtNum(spec.getPtNum());
                entity.setPtTimePeriod(spec.getPtTimePeriod());
            }
            list.add(entity);
        });
        return goodsMapper.updateSpecs(list) > 0;
    }

    public boolean updateDetails(Integer goodsId, List<GoodsDetailDto> details) {
        if (CollectionUtils.isEmpty(details)) {
            return true;
        }
        List<GoodsDetailEntity> list = new ArrayList<>();
        details.forEach(detail -> {
            GoodsDetailEntity entity = new GoodsDetailEntity();
            entity.setId(detail.getDetailId());
            entity.setGoodsId(goodsId);
            entity.setTitle(detail.getTitle());
            entity.setIntro(detail.getIntro());
            entity.setImgs(CollectionUtils.isEmpty(detail.getImgs()) ? null : Joiner.on(",").join(detail.getImgs()));
            entity.setSort(detail.getSort());
            list.add(entity);
        });
        return goodsMapper.updateDetails(list) > 0;
    }

    public boolean deleteSpecs(List<Integer> specIds) {
        if (CollectionUtils.isEmpty(specIds)) {
            return true;
        }
        return goodsMapper.deleteSpecs(specIds) > 0;
    }

    public boolean deleteDetails(List<Integer> detailIds) {
        if (CollectionUtils.isEmpty(detailIds)) {
            return true;
        }
        return goodsMapper.deleteDetails(detailIds) > 0;
    }

    public boolean deleteGoods(Integer goodsId) {
        return goodsMapper.deleteGoods(goodsId) > 0;
    }


    public GoodsEntity queryGoodInfo(int goodsId) {
        return goodsMapper.queryDetail(goodsId);
    }

    /**
     * 列表查询
     *
     * @param query
     * @return
     */
    public List<GoodsEntity> listGoods(GoodsQueryReq query) {
        if (StringUtils.isBlank(query.getName())) {
            query.setName(null);
        }
        return goodsMapper.listGoods(query);
    }

    public int goodsCount(GoodsQueryReq query) {
        return goodsMapper.goodsCount(query);
    }


    /**
     * 返回商品基础信息，不包含详情与尺寸信息
     *
     * @param query
     * @return
     */
    public List<GoodsEntity> listSimpleGoods(GoodsQueryReq query) {
        if (StringUtils.isBlank(query.getName())) {
            query.setName(null);
        }
        return goodsMapper.listSimpleGoods(query);
    }
}
